package com.engine.shunsheng.controller;

import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import com.engine.shunsheng.service.LeaveDevService;
import com.engine.shunsheng.service.impl.LeaveDevServiceImpl;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author chenwnj
 * @date 2023/11/14
 * @description
 **/
public class LeaveDevController {

    public LeaveDevService getLeaveDevService(User user) {
        return ServiceUtil.getService(LeaveDevServiceImpl.class,user);
    }

    @POST
    @Path("/getLeaveDuration")
    @Produces(MediaType.APPLICATION_JSON)
    public String getLeaveDuration(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> params = ParamUtil.request2Map(request);
        Map<String, Object> resultDatas = getLeaveDevService(user).getLeaveDuration(params);
        return  new Gson().toJson(resultDatas);
    }

    @POST
    @Path("/syncHbInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public String syncHbInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, Object> params = ParamUtil.request2Map(request);
        Map<String, Object> result = new HashMap<>();
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("syncHbInfo start.");
        try {
            String yearParam = Util.null2String(params.get("yearParam"));
            RecordSet rs = new RecordSet();

            // 获取当前时间
            LocalDateTime currentTime = LocalDateTime.now();
            // 定义格式化模式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
            // 格式化当前时间
            String formattedTime = currentTime.format(formatter);

            // 获取假期单位
            Map<String, String> leaveAndUnitMap = new HashMap<>();
            rs.execute("SELECT id, minimumUnit FROM KQ_LeaveRules");
            while (rs.next()) {
                String id = rs.getString("id");
                String minimumUnit = rs.getString("minimumUnit");
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                leaveAndUnitMap.put(id, minimumUnit);
            }
            String sqlQuery = "Select t1.id,t1.leaveRulesId,t1.baseAmount,t1.tiaoxiuamount, t1.usedAmount,t1.extraAmount,t1.resourceId,t1.expirationDate,t1.effectiveDate,\n" +
                    " t1.belongYear,t1.belongMonth,\n" +
                    " case when t5.subcompanycode ='8008' then 0 \n" +
                    " when t6.departmentcode like '8010-6112%' or t6.departmentcode like '8010-6113%' then 1 \n" +
                    " when t5.subcompanycode = '8009' or t5.subcompanycode = '8014' or t5.subcompanycode = '8015' then 2 \n" +
                    " when t6.departmentcode like '8010-6111%' then 3 \n" +
                    " else 0 end as ssdq,\n" +
                    " case when t4.field13 =1 then '4' \n" +
                    " when t4.field13 =5 then '6'\n" +
                    " when t5.subcompanycode ='8008' then '0' \n" +
                    " when (t5.subcompanycode = '8009' or t5.subcompanycode = '8014' or t5.subcompanycode = '8015') and t4.field13 =2  then '2' \n" +
                    " when (t5.subcompanycode = '8009' or t5.subcompanycode = '8014' or t5.subcompanycode = '8015') and t4.field13 =3  then '5' \n" +
                    " when t6.departmentcode like '8010-6111%' then '3' \n" +
                    " when t6.departmentcode like '8010-6112%' or t6.departmentcode like '8010-6113%' then '1' \n" +
                    " else '0' end as rylb,t7.rylx, t8.duration \n" +
                    " from kq_balanceOfLeave t1\n" +
                    " right join HrmResource  t2 on t1.resourceId=t2.id\n" +
                    " left join cus_fielddata t3 on t1.resourceId=t3.id and t3.scopeid=3\n" +
                    " left join cus_fielddata t4 on t1.resourceId=t4.id and t4.scopeid=1\n" +
                    " left join HrmSubCompany t5 on t2.subcompanyid1=t5.id\n" +
                    " left join HrmDepartment t6 on t6.id=t2.departmentid\n" +
                    " right join uf_JQLXKJPZB t7 on t7.jq=t1.leaveRulesId \n" +
                    " and t7.rylx like \n" +
                    " (case when t4.field13 =1 then '%4%' \n" +
                    " when t4.field13 =5 then '%6%'\n" +
                    " when t5.subcompanycode ='8008' then '%0%' \n" +
                    " when (t5.subcompanycode = '8009' or t5.subcompanycode = '8014' or t5.subcompanycode = '8015') and t4.field13 =2  then '%2%' \n" +
                    " when (t5.subcompanycode = '8009' or t5.subcompanycode = '8014' or t5.subcompanycode = '8015') and t4.field13 =3  then '%5%' \n" +
                    " when t6.departmentcode like '8010-6111%' then '%3%' \n" +
                    " when t6.departmentcode like '8010-6112%' or t6.departmentcode like '8010-6113%' then '%1%' \n" +
                    " else '%0%' end) and (t7.xb=t2.sex or t7.xb is null)\n" +
                    " left join (select a.* from KQ_ATT_VACATION a left join workflow_requestbase b on a.requestid=b.requestid " +
                    "    where a.status=1 and b.requestid > 0) t8 on t8.resourceId = t1.resourceId and t8.newLeaveType = t1.leaveRulesId" +
                    " where  t2.status in (0,1,2,3) and t1.baseAmount+tiaoxiuamount>0 and belongYear=?";
            rs.executeQuery(sqlQuery, yearParam);

            String modeId = "400";
            String modedatacreater = "1";
            String modedatacreatertype = "0";
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");//设置日期格式
            List<List> tmpList = new ArrayList<>();
            while (rs.next()) {
                String id = rs.getString("balanceId");
                String resourceId = rs.getString("resourceId");
                String leaveRulesId = rs.getString("leaveRulesId");
                String baseAmountT = rs.getString("baseAmount");
                if (StringUtils.isEmpty(baseAmountT)) {
                    baseAmountT = "0.0";
                }
                String usedAmountT = rs.getString("usedAmount");
                if (StringUtils.isEmpty(usedAmountT)) {
                    usedAmountT = "0.0";
                }
                String extraAmountT = rs.getString("extraAmount");
                if (StringUtils.isEmpty(extraAmountT)) {
                    extraAmountT = "0.0";
                }
                String tiaoxiuamountT = rs.getString("tiaoxiuamount");
                if (StringUtils.isEmpty(tiaoxiuamountT)) {
                    tiaoxiuamountT = "0.0";
                }
                String duration = rs.getString("duration");
                if (StringUtils.isEmpty(duration)) {
                    duration = "0.0";
                }
                String expirationDate = rs.getString("expirationDate");
                String effectiveDate = rs.getString("effectiveDate");
                String belongYear = rs.getString("belongYear");
                String belongMonth = rs.getString("belongMonth");
                String ssdq = rs.getString("ssdq");
                double baseAmount = Double.parseDouble(baseAmountT);
                double extraAmount = Double.parseDouble(extraAmountT);
                double usedAmount = Double.parseDouble(usedAmountT);
                double tiaoxiuamount = Double.parseDouble(tiaoxiuamountT);

                String minimumUnit = leaveAndUnitMap.get(leaveRulesId);
                String dw = "2";
                if (StringUtils.equals(minimumUnit, "1") || StringUtils.equals(minimumUnit, "2") || StringUtils.equals(minimumUnit, "4")) {
                    dw = "0";
                }
                if (StringUtils.equals(minimumUnit, "3") || StringUtils.equals(minimumUnit, "5") || StringUtils.equals(minimumUnit, "6")) {
                    dw = "1";
                }

                if (StringUtils.isNotEmpty(belongMonth) && belongMonth.length() == 2 && belongMonth.startsWith("0")) {
                    belongMonth = belongMonth.substring(1, 2);
                }

                if (!StringUtils.equals(leaveRulesId, "5")) {
                    String str = resourceId + "+" + leaveRulesId + "+" + belongYear + "+" + baseAmount + "+" + "neither";
                    double canUseAmount = Util.getDoubleValue(getCanUseAmount(id, str), 0.00);
                    String restAmount = String.format("%.2f", canUseAmount + extraAmount - usedAmount);
                    /*获取今天的日期、此刻的时间*/
                    Calendar today = Calendar.getInstance();
                    String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                            + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                            + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);

                    boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, resourceId, belongYear, currentDate, effectiveDate, expirationDate);
                    String statusStr = null;
                    if (status) {
                        statusStr = "0";
                    } else {
                        statusStr = "1";
                    }

                    String uuid = UUID.randomUUID().toString();
                    String nowDate = sdfDate.format(new Date());
                    String nowTime = sdfTime.format(new Date());
                    List rowParam = new ArrayList<>();
                    rowParam.add(resourceId);
                    rowParam.add(leaveRulesId);
                    rowParam.add(baseAmount);
                    rowParam.add(extraAmount);
                    rowParam.add(usedAmount);
                    rowParam.add(restAmount);
                    rowParam.add(expirationDate);
                    rowParam.add(canUseAmount);
                    rowParam.add(statusStr);
                    rowParam.add(belongYear);
                    rowParam.add(belongMonth);
                    rowParam.add(ssdq);

                    rowParam.add(modeId);
                    rowParam.add(uuid);
                    rowParam.add(modedatacreater);
                    rowParam.add(modedatacreatertype);
                    rowParam.add(nowDate);
                    rowParam.add(nowTime);
                    rowParam.add(duration);
                    rowParam.add(dw);
                    rowParam.add(formattedTime);
                    tmpList.add(rowParam);
                } else {
                    double edjs = baseAmount + extraAmount + tiaoxiuamount;
                    String statusStr = "0";
                    if (StringUtils.isNotEmpty(expirationDate)) {
                        // 定义日期格式
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String today = cn.hutool.core.date.DateUtil.format(new Date(), "yyyy-MM-dd");
                        // 将日期字符串解析为Date对象
                        Date date1 = dateFormat.parse(today);
                        Date date2 = dateFormat.parse(expirationDate);
                        if (date2.compareTo(date1) < 0) {
                            statusStr = "1";
                        }
                    }

                    String uuid = UUID.randomUUID().toString();
                    String nowDate = sdfDate.format(new Date());
                    String nowTime = sdfTime.format(new Date());
                    List rowParam = new ArrayList<>();
                    rowParam.add(resourceId);
                    rowParam.add(leaveRulesId);
                    rowParam.add(String.format("%.2f", edjs));
                    rowParam.add(String.format("%.2f", extraAmount));
                    rowParam.add(String.format("%.2f", usedAmount));
                    rowParam.add(String.format("%.2f", edjs - usedAmount));
                    rowParam.add(expirationDate);
                    rowParam.add(String.format("%.2f", edjs));
                    rowParam.add(statusStr);
                    rowParam.add(belongYear);
                    rowParam.add(belongMonth);
                    rowParam.add(ssdq);

                    rowParam.add(modeId);
                    rowParam.add(uuid);
                    rowParam.add(modedatacreater);
                    rowParam.add(modedatacreatertype);
                    rowParam.add(nowDate);
                    rowParam.add(nowTime);
                    rowParam.add(duration);
                    rowParam.add(dw);
                    rowParam.add(formattedTime);
                    tmpList.add(rowParam);
                }
            }

            if (!CollectionUtils.isEmpty(tmpList)) {
                String insertSql = "INSERT INTO uf_jqyubf (yg,jqlx,edjs,ewed,yyed,syed,edyxq,ysfed,zt,sznf,szyf,szdq,formmodeid," +
                        "MODEUUID, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime,zted,dw,pch) " +
                        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                rs.executeBatchSql(insertSql, tmpList);
                // 权限重构
                ModeRightInfo modeRightInfo = new ModeRightInfo();
                modeRightInfo.setNewRight(true);
                modeRightInfo.editModeDataShare(1, Integer.parseInt(modeId), Integer.parseInt("403"));
            }
        } catch (Exception e) {
            baseBean.writeLog("syncHbInfo error:" + e.getMessage());
            result.put("mes", "系统错误，请联系管理员！");
            result.put("code", "400");
        }
        result.put("mes", "同步完成！");
        result.put("code", "200");
        return  new Gson().toJson(result);
    }

    public String getCanUseAmount(String balanceId, String otherPara) {
        BigDecimal canUseAmount = new BigDecimal(0);
        try {
            String otherParaArr[] = otherPara.split("\\+", 5);
            String resourceId = otherParaArr[0];
            String leaveRulesId = otherParaArr[1];
            String belongYear = otherParaArr[2];
            BigDecimal baseAmount = new BigDecimal(Util.null2s(otherParaArr[3].trim(), "0"));
            String legalOrWelfare = Util.null2String(otherParaArr[4]);

            /*获取当前日期*/
            String date = DateUtil.getCurrentDate();

            canUseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(resourceId, leaveRulesId, belongYear, baseAmount, legalOrWelfare, date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return canUseAmount.setScale(2, RoundingMode.HALF_UP).toPlainString();
    }

}
